﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Icms.Core;
using Icms.Core.Model;
using Icms.Core.Repository;
using Icms.Resources;

namespace Icms.WebUI.Controllers
{
    public class ParameterAjaxDropdownController : Controller
    {
        private readonly IRepo<Parameter> r;

        public ParameterAjaxDropdownController(IRepo<Parameter> r)
        {
            this.r = r;
        }

        public ActionResult GetItems(Guid? key, Guid? parent, string code, Guid? caseKind, bool? requiresCourt, bool? requiresParent)
        {
            var list = new List<SelectListItem> { new SelectListItem { Text = Mui.not_selected, Value = "" } };

            var result = Enumerable.Empty<Parameter>();
            if (parent.HasValue)
            {
                var parameter = r.Get(parent.Value);
                result = r.Where(o => o.ClassifierId == parameter.ChildClassifierId);
            }
            else if (code != null)
            {
                if (requiresParent.HasValue && !caseKind.HasValue)
                {
                }
                else
                {
                    result = r.Where(o => o.Classifier.Code == code);
                    if (caseKind.HasValue) result = result.Where(o => o.Classifier.CaseKind.Value == caseKind.Value.CaseKind());
                    if (requiresCourt.HasValue)
                    {
                        var court = Globals.Court();
                        result = result.Where(o => o.Classifier.InstanceKind.HasValue && o.Classifier.InstanceKind.Value == court.CourtType.Code);
                    }
                }
            }


            list.AddRange(result.Select(o => new SelectListItem
                                                  {
                                                      Text = o.Title,
                                                      Value = o.Id.ToString(),
                                                      Selected = o.Id == key
                                                  }));
            return Json(list);
        }
    }
}